import storage from './storage'
import config from './config'
import env from './env'

let loadingCount = 0

const showLoading = show => {
    if (show) {
        loadingCount++
        uni.showLoading()
        return show
    }
}

const hideLoading = show => {
    if (show) {
        loadingCount--
        setTimeout(()=>{
            if (loadingCount === 0) {
                uni.hideLoading()
            }
        },60)
    }
}

const request = options => {
    
    const url = options.url ?? env.baseUrl + options.uri
    const method = options.method ?? 'GET'
    const header = options.header ?? {}
    if (env.$baseUrl) {
        header['x-base-url'] = env.$baseUrl
    }
    const token = storage.get(storage.token)
    if (token) {
        header[config.tokenName] = token
    }
    const data = options.data
    if (method === 'GET' && data) {
        for (let key of Object.keys(data)) {
            if (data[key] === null) {
                delete data[key]
            }
        }
    }
    const timeout = options.timeout ?? 10000
    const enableCache = options.enableCache ?? false
    
    return new Promise((resolve, reject) => {
        const loadingToken = showLoading(options.loading ?? true)
        
        uni.request({
            method,url,header,data,timeout,enableCache,
            success: res => {
                resolve(res.data)
            },
            fail: error => {
                reject(error)
                console.error('request', error)
            },
            complete: () => {
                hideLoading(loadingToken)
            }
        })
    })
}

export default {
    request,
    get: (uri, params = null, options = {}) => request({
        method: 'GET',
        uri: uri,
        data: params,
        ...options
    }),
    post: (uri, data = null, options = {}) => request({
        method: 'POST',
        uri: uri,
        data: data,
        header: {
            'Content-Type': 'application/json; charset=utf-8'
        },
        ...options
    }),
    put: (uri, data = null, options = {}) => request({
        method: 'PUT',
        uri: uri,
        data: data,
        header: {
            'Content-Type': 'application/json; charset=utf-8'
        },
        ...options
    }),
    delete: (uri, data = null, options = {}) => request({
        method: 'DELETE',
        uri: uri,
        data: data,
        header: {
            'Content-Type': 'application/json; charset=utf-8'
        },
        ...options
    })
}
